import store from "../store"
// let RongIMVoice=window.RongIMVoice = RongIMLib.RongIMVoice;
//   RongIMVoice.init();
export default class createMessage  {
  //instance
  constructor(){
    this.appKey="bmdehs6pbg9ss";
    this.appUserToken=store.state.rong.token;
    console.warn('=====',this.appUserToken)
    this.uid=Number(store.state.rong.union_id)
    this.RongIMEmoji = RongIMLib.RongIMEmoji;
    this.initClinet();
    this.initAddListener();
    this.AddListenerMessage()
    this.ClientConnect();

  }
  /**
   *  ClinetSuccess 链接成功
   */
  ClinetSuccess(uid){
    console.warn('链接成功uid',uid)
  }
  /**
   *  postMessage 发送消息
   */
   postMessage(content,target,way){
    let that = this;
    return new Promise((res,reject)=>{

      let msg = new RongIMLib.TextMessage({content:content,extra:target});
      msg.user = {'union_id':store.state.rong.union_id,'name':store.state.rong.name,uid:store.state.rong.uid}
      let type = RongIMLib.ConversationType.PRIVATE;
      let pushData = `${store.state.rong.name}的消息来了`;
      RongIMClient.getInstance().sendMessage(type, target.union_id, msg, {
        onSuccess: function (message) {
          // console.warn('消息发送成功',message.content);
          message.content.content = RongIMLib.RongIMEmoji.symbolToHTML(message.content.content)
           let mess=message.content;
           let content ={
            ...mess,
            // ctime_show : that.format(message.sentTime),
            ctime_show : message.sentTime,
            isLeft : false
           }
           
          //读取数据库  获取消息  如有目标用户则修改 否则添加该用户消息
          DB.read('huahui_chat',`target_${target.uid}`,content,way)
          res(content)
        },
        onError: function (errorCode,message){
          reject('no ok')
        }
      }, false, pushData);
    })
  }
  /**
   *  initClinet 公有云初始化
   */
  initClinet(){
    RongIMLib.RongIMClient.init(this.appKey);
    this.instance = RongIMClient.getInstance();
    this.RongIMEmoji.init()
  }
  /**
   *  getConversationList 获取列表
   */
  getConversationList(){
    let that=this;
    this.instance.getConversationList({
      onSuccess: function(list) {
        console.warn('融云列表获取成功',list)
      },
      onError: function(error) {
        console.log(error)
      }
    },null);
  }
  /**
   *  initAddListener 连接状态监听器
   */
  initAddListener(){
    let that=this;
    RongIMClient.setConnectionStatusListener({
      onChanged: function (status) {
        switch (status) {
          case RongIMLib.ConnectionStatus.CONNECTED:
            that.getConversationList()
            break;
          case RongIMLib.ConnectionStatus.CONNECTING:
            console.log('正在链接');
            break;
          case RongIMLib.ConnectionStatus.DISCONNECTED:
            console.log('断开连接');
            break;
          case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
            console.log('其他设备登录');
            break;
          case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
            console.log('域名不正确');
            break;
          case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
            console.log('网络不可用');
            break;
        }
      }
    });
  }
  /**
   *  AddListenerMessage 监听消息
   */
  AddListenerMessage(){
    let that=this
    let num = 0
    let single = 0
    RongIMClient.setOnReceiveMessageListener({
      // 接收到的消息
      onReceived: function (message) {
          // 判断消息类型
          let content = ''
          let mess = ''
          console.log(message.content)
          switch(message.messageType){
              case RongIMClient.MessageType.TextMessage:
                  // message.content.content => 文字内容
                  message.content.content = RongIMLib.RongIMEmoji.symbolToHTML(message.content.content)
                  mess=message.content;
                  content ={
                    ...mess,
                    ctime_show : message.sentTime,
                    isLeft : true
                  }
                  break;
              case RongIMClient.MessageType.VoiceMessage:
                  // message.content.content => 格式为 AMR 的音频 base64
                  break;
              case RongIMClient.MessageType.ImageMessage:
                  // message.content.content => 图片缩略图 base64
                  // message.content.imageUri => 原图 URL
                  break;
              case RongIMClient.MessageType.LocationMessage:
                  // message.content.latiude => 纬度
                  // message.content.longitude => 经度
                  // message.content.content => 位置图片 base64
                  break;
              case RongIMClient.MessageType.RichContentMessage:
                  // message.content.content => 文本消息内容
                  // message.content.imageUri => 图片 base64
                  // message.content.url => 原图 URL
                  break;
              case RongIMClient.MessageType.InformationNotificationMessage:
                  // do something
                  break;
              case RongIMClient.MessageType.ContactNotificationMessage:
                  // do something
                  break;
              case RongIMClient.MessageType.ProfileNotificationMessage:
                  // do something
                  break;
              case RongIMClient.MessageType.CommandNotificationMessage:
                  // do something
                  break;
              case RongIMClient.MessageType.CommandMessage:
                  // do something
                  break;
              case RongIMClient.MessageType.UnknownMessage:
                  // do something
                  break;
              default:
                  // do something
          }
          //读取数据库  获取消息  如有目标用户则修改 否则添加该用户消息
          DB.read('huahui_chat',`target_${mess.user.uid}`,content)
      }
    });
  }
  /**
   *  ClientConnect 链接
   */
  ClientConnect(){
    let that=this
    RongIMClient.connect(this.appUserToken, {

      onSuccess: function (userId) {
        that.ClinetSuccess(userId)
      },
      onTokenIncorrect: function () {
        console.log('token无效');
      },
      onError: function (errorCode) {
        var info = '';
        switch (errorCode) {
          case RongIMLib.ErrorCode.TIMEOUT:
            info = '超时';
            break;
          case RongIMLib.ErrorCode.UNKNOWN_ERROR:
            info = '未知错误';
            break;
          case RongIMLib.ErrorCode.UNACCEPTABLE_PaROTOCOL_VERSION:
            info = '不可接受的协议版本';
            break;
          case RongIMLib.ErrorCode.IDENTIFIER_REJECTED:
            info = 'appkey不正确';
            break;
          case RongIMLib.ErrorCode.SERVER_UNAVAILABLE:
            info = '服务器不可用';
            break;
        }
        console.log(info);
      }
    });
  }
  /**
   *  时间戳转换
   */
  format(times)
  {
    //shijianchuo是整数，否则要parseInt转换
    var time = new Date(times);
    var y = time.getFullYear();
    var m = time.getMonth()+1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return this.add0(m)+'-'+this.add0(d)+' '+this.add0(h)+':'+this.add0(mm);
  }
  add0(m){
    return m<10?'0'+m:m 
  }
}
